package com.financial.service.heemoney.service.impl;

import com.financial.service.heemoney.constants.FinancialRefundHeemoneyEnumConstants;
import com.financial.service.heemoney.convertor.HeemoneyRefundConvert;
import com.financial.service.heemoney.convertor.HeemoneyRefundQueryConvert;
import com.financial.service.heemoney.dao.FinancialRefundHeemoneyDao;
import com.financial.service.heemoney.domain.FinancialRefundHeemoneyDO;
import com.financial.service.heemoney.dto.HeemoneyConfigDTO;
import com.financial.service.heemoney.dto.businsess.HeemoneyRefundBusinessDTO;
import com.financial.service.heemoney.dto.businsess.HeemoneyRefundQueryBusinessDTO;
import com.financial.service.heemoney.dto.commmon.HeemoneyRefundCommonDTO;
import com.financial.service.heemoney.dto.commmon.HeemoneyRefundQueryCommonDTO;
import com.financial.service.heemoney.dto.inparameter.HeemoneyRefundInParamDTO;
import com.financial.service.heemoney.dto.inparameter.HeemoneyRefundQueryInParamDTO;
import com.financial.service.heemoney.dto.param.HeemoneyRefundParamDTO;
import com.financial.service.heemoney.dto.param.HeemoneyRefundQueryParamDTO;
import com.financial.service.heemoney.service.FinancialRefundHeemoneyService;
import com.financial.service.heemoney.utils.JsonUtils;
import com.financial.service.heemoney.utils.OkHttpUtils;
import com.financial.service.heemoney.utils.apiresult.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class FinancialRefundHeemoneyServiceImpl implements FinancialRefundHeemoneyService {
    @Autowired
    private FinancialRefundHeemoneyDao financialRefundHeemoneyDao;

    @Autowired
    private OkHttpUtils okHttpUtils;

    public static final Logger log = LoggerFactory.getLogger(FinancialPayHeemoneyServiceImpl.class);

    @Override
    public ApiResult refund(HeemoneyRefundInParamDTO heemoneyRefundInParamDTO) {
        log.info("FinancialRefundHeemoneyServiceImpl----调用金融中心汇收银服务层商户退款申请接口前参数打印：{}", JsonUtils.beanToJson(heemoneyRefundInParamDTO));
        //数据转实体校验参数非空
        HeemoneyRefundCommonDTO heemoneyRefundCommonDTO = HeemoneyRefundConvert.MAPPER.configConvertCommonDTO(new HeemoneyConfigDTO(), heemoneyRefundInParamDTO);
        HeemoneyRefundBusinessDTO heemoneyRefundBusinessDTO = HeemoneyRefundConvert.MAPPER.convertBusinessDTO(heemoneyRefundInParamDTO);
        HeemoneyRefundParamDTO heemoneyRefundParamDTO = new HeemoneyRefundParamDTO(heemoneyRefundCommonDTO, heemoneyRefundBusinessDTO);
        log.info("http请求汇收银服务层商户退款申请接口入参：{}", heemoneyRefundParamDTO.getJsonParam());
        try {
            String resultStr = okHttpUtils.postJsonParams(new HeemoneyConfigDTO().getHeemoneyRefund().getRequest_url(), heemoneyRefundParamDTO.getJsonParam());
            log.info("http请求汇收银服务层商户退款申请接口回执:{}", resultStr);
            //退款主信息保存
            saveRefundInfo(heemoneyRefundInParamDTO, resultStr);
            //拼接调用者返回数据结构
            Map<String, Object> changeMap = JsonUtils.jsonToMap(resultStr);
            if (changeMap.get("result_code").equals("SUCCESS")) {
                Map<String, Object> resultMap = new HashMap<>();
                //商户号
                resultMap.put("mch_uid", changeMap.get("mch_uid"));
                //商户订单号
                resultMap.put("out_trade_no", changeMap.get("out_trade_no"));
                //商户退款单号
                resultMap.put("out_refund_no", changeMap.get("out_refund_no"));
                //退款总金额,
                resultMap.put("refund_fee", changeMap.get("refund_fee"));
                //实际退款金额
                resultMap.put("real_refund_fee", changeMap.get("real_refund_fee"));
                //返回调用信息
                return ApiResult.success(resultMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("http请求汇收银服务层商户退款申请接口失败，退款单号：{}", heemoneyRefundInParamDTO.getOut_refund_no());
        }
        return ApiResult.failure();
    }

    @Override
    public ApiResult refundQuery(HeemoneyRefundQueryInParamDTO heemoneyRefundQueryInParamDTO) {
        log.info("FinancialRefundHeemoneyServiceImpl----调用金融中心汇收银服务层商户退款查询接口参数打印：{}", JsonUtils.beanToJson(heemoneyRefundQueryInParamDTO));
        //数据转实体校验参数非空
        HeemoneyRefundQueryCommonDTO heemoneyRefundQueryCommonDTO = HeemoneyRefundQueryConvert.MAPPER.configConvertCommonDTO(new HeemoneyConfigDTO(), heemoneyRefundQueryInParamDTO);
        HeemoneyRefundQueryBusinessDTO heemoneyRefundQueryBusinessDTO = HeemoneyRefundQueryConvert.MAPPER.convertBusinessDTO(heemoneyRefundQueryInParamDTO);
        HeemoneyRefundQueryParamDTO heemoneyRefundQueryParamDTO = new HeemoneyRefundQueryParamDTO(heemoneyRefundQueryCommonDTO, heemoneyRefundQueryBusinessDTO);
        log.info("http请求汇收银服务层商户退款申请接口入参：{}", heemoneyRefundQueryParamDTO.getJsonParam());
        try {
            String resultStr = okHttpUtils.postJsonParams(new HeemoneyConfigDTO().getHeemoneyRefundQuery().getRequest_url(), heemoneyRefundQueryParamDTO.getJsonParam());
            log.info("http请求汇收银服务层商户退款查询接口回执:{}", resultStr);

            //拼接调用者返回数据结构
            Map<String, Object> changeMap = JsonUtils.jsonToMap(resultStr);
            if (changeMap.get("result_code").equals("SUCCESS") && changeMap.get("return_code").equals("SUCCESS")) {
                Map<String, Object> resultMap = new HashMap<>();
                //商户号
                resultMap.put("mch_uid", changeMap.get("mch_uid"));
                //商户订单号
                resultMap.put("out_trade_no", changeMap.get("out_trade_no"));
                //商户退款单号
                resultMap.put("out_refund_no", changeMap.get("out_refund_no"));
                //退款总金额,
                resultMap.put("refund_fee", changeMap.get("refund_fee"));
                //实际退款金额
                resultMap.put("real_refund_fee", changeMap.get("real_refund_fee"));
                //退款状态：Undeal=退款处理中，Success=退款成功，Failure=退款失败
                resultMap.put("refund_status", changeMap.get("refund_status"));
                //返回调用信息
                return ApiResult.success(resultMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("http请求汇收银服务层商户退款查询接口失败，退款单号：{}", heemoneyRefundQueryInParamDTO.getOut_refund_no());
        }
        return ApiResult.failure();
    }


    private void saveRefundInfo(HeemoneyRefundInParamDTO heemoneyRefundInParamDTO, String resultStr) {
        Object temp = "";
        Map<String, Object> changeMap = JsonUtils.jsonToMap(resultStr);
        temp = changeMap.get("result_code");
        String result_code = temp != null ? temp.toString() : null;
        temp = changeMap.get("return_code");
        String return_code = temp != null ? temp.toString() : null;
        FinancialRefundHeemoneyDO financialRefundHeemoneyDO = new FinancialRefundHeemoneyDO();

        if (result_code.equals("SUCCESS") && return_code.equals("SUCCESS")) {
            financialRefundHeemoneyDO.setState(FinancialRefundHeemoneyEnumConstants.ENUM_STATE_SUC);
            financialRefundHeemoneyDO.setReturnMessage(changeMap.get("result_msg").toString());
        } else if (return_code.equals("SUCCESS") && !result_code.equals("SUCCESS")) {
            financialRefundHeemoneyDO.setState(FinancialRefundHeemoneyEnumConstants.ENUM_STATE_FAIL);
            financialRefundHeemoneyDO.setReturnMessage(changeMap.get("error_msg").toString());
        } else {
            financialRefundHeemoneyDO.setState(FinancialRefundHeemoneyEnumConstants.ENUM_STATE_FAIL);
            financialRefundHeemoneyDO.setReturnMessage("调用失败");
        }
        BeanUtils.copyProperties(heemoneyRefundInParamDTO, financialRefundHeemoneyDO);
        financialRefundHeemoneyDO.setGmtCreate(new Date());
        financialRefundHeemoneyDO.setGmtModified(new Date());
        financialRefundHeemoneyDO.setIsDelete(FinancialRefundHeemoneyEnumConstants.ENUM_ISDELETE_UNDEL);
        financialRefundHeemoneyDao.save(financialRefundHeemoneyDO);
    }


    @Override
    public FinancialRefundHeemoneyDO get(Integer id) {
        return financialRefundHeemoneyDao.get(id);
    }

    @Override
    public List<FinancialRefundHeemoneyDO> list(Map<String, Object> map) {
        return financialRefundHeemoneyDao.list(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return financialRefundHeemoneyDao.count(map);
    }

    @Override
    public int save(FinancialRefundHeemoneyDO financialRefundHeemoney) {
        return financialRefundHeemoneyDao.save(financialRefundHeemoney);
    }

    @Override
    public int update(FinancialRefundHeemoneyDO financialRefundHeemoney) {
        return financialRefundHeemoneyDao.update(financialRefundHeemoney);
    }

    @Override
    public int remove(Integer id) {
        return financialRefundHeemoneyDao.remove(id);
    }

    @Override
    public int batchRemove(Integer[] ids) {
        return financialRefundHeemoneyDao.batchRemove(ids);
    }


}
